package com.zkrt.upms.common.component;

import cn.hutool.core.util.RandomUtil;
import com.github.tocrhz.mqtt.autoconfigure.MqttConfigurer;
import com.github.tocrhz.mqtt.properties.ConnectionProperties;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Data
@Component
public class MqttConfigSetter extends MqttConfigurer {

    @Value("${mqtt.config.host}")
    private String host;

    @Value("${mqtt.config.port}")
    private String port;

    @Value("${mqtt.config.username}")
    private String username;

    @Value("${mqtt.config.password}")
    private String password;

    @Value("${mqtt.config.clientid}")
    private String clientid;

    @Override
    public void beforeCreate(ClientRegistry registry) {
        if (registry != null) {
            registry.clear();
            String systemClientID = String.format("%s-%s", clientid, RandomUtil.randomNumbers(9));
            log.info("[MQTT.ClientID] -> {}", systemClientID);
            log.info("[MQTT.HOST] -> {}", host);
            log.info("[MQTT.PORT] -> {}", port);
            log.info("[MQTT.USERNAME] -> {}", username);
            log.info("[MQTT.PASSWORD] -> {}", password);
            ConnectionProperties properties = new ConnectionProperties();
            String uri = String.format("tcp://%s:%s", host, port);
            properties.setUri(new String[]{uri});
            properties.setClientId(systemClientID);
            properties.setUsername(username);
            properties.setPassword(password);
            properties.setCleanSession(true);
            properties.setConnectionTimeout(10);
            properties.setKeepAliveInterval(20);
            properties.setEnableSharedSubscription(true);
            registry.add(systemClientID, properties);
        }
    }
}
